import { createStore } from 'vuex';
import axios from 'axios';

// 初始化状态
const getInitialState = () => ({
    tagsList: [],
    collapse: false,
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
    rememberMe: localStorage.getItem('rememberMe') === 'true'
});

export default createStore({
    state: getInitialState(),

    mutations: {
        // Tags 相关操作
        delTagsItem(state, data) {
            state.tagsList.splice(data.index, 1);
        },
        setTagsItem(state, data) {
            state.tagsList.push(data);
        },
        clearTags(state) {
            state.tagsList = [];
        },
        closeTagsOther(state, data) {
            state.tagsList = data;
        },
        closeCurrentTag(state, { currentPath, router }) {
            const index = state.tagsList.findIndex(item => item.path === currentPath);
            if (index !== -1) {
                if (index < state.tagsList.length - 1) {
                    router.push(state.tagsList[index + 1].path);
                } else if (index > 0) {
                    router.push(state.tagsList[index - 1].path);
                } else {
                    router.push("/");
                }
                state.tagsList.splice(index, 1);
            }
        },

        // 认证相关操作
        SET_TOKEN(state, { token, rememberMe }) {
            state.token = token;
            state.rememberMe = rememberMe;
            if (rememberMe) {
                localStorage.setItem('token', token);
                localStorage.setItem('rememberMe', 'true');
            } else {
                sessionStorage.setItem('token', token);
            }
        },

        SET_USERINFO(state, { userInfo, rememberMe }) {
            state.userInfo = userInfo;
            if (rememberMe) {
                localStorage.setItem('userInfo', JSON.stringify(userInfo));
            } else {
                sessionStorage.setItem('userInfo', JSON.stringify(userInfo));
            }
        },

        LOGOUT(state) {
            state.token = '';
            state.userInfo = {};
            state.rememberMe = false;
            localStorage.removeItem('token');
            localStorage.removeItem('userInfo');
            localStorage.removeItem('rememberMe');
            sessionStorage.removeItem('token');
            sessionStorage.removeItem('userInfo');
        }
    },

    getters: {
        isAuthenticated: state => !!state.token,
        currentUser: state => state.userInfo,
        userId: state => state.userInfo?.userId || '',
        userRole: state => state.userInfo?.role || '',
        rememberMe: state => state.rememberMe
    },

    actions: {
        async updateAuth({ commit }, { token, userInfo, rememberMe = false }) {
            commit('SET_TOKEN', { token, rememberMe });
            commit('SET_USERINFO', { userInfo, rememberMe });
        },

        async logout({ commit, state }) {
            try {
                // 创建axios实例，设置baseURL
                const logoutAxios = axios.create({
                    baseURL: 'http://localhost:8800'
                });
                
                // 设置Authorization头
                const config = {
                    headers: {
                        'Authorization': `Bearer ${state.token}`
                    }
                };
                await logoutAxios.post('/user/logout', {}, config);
            } catch (error) {
                console.error('退出API调用失败:', error);
            } finally {
                commit('LOGOUT');
            }
        },

        checkAuth({ state }) {
            return !!state.token;
        }
    },

    modules: {}
});